package com.danger.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.danger.Adapter.FileListAdapter;
import com.danger.Model.FileInfo;
import com.danger.Service.DownloadService;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private List<FileInfo> fileInfos;
    private FileListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(DownloadService.ACTION_UPDATE);
        filter.addAction(DownloadService.ACTION_FINISHED);
        registerReceiver(receiver, filter);

        initView();
        initEvent();
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.listView);
        fileInfos = new ArrayList<>();

        FileInfo fileInfo1 = new FileInfo(0, "http://c5.97you.net/download/颜色拾取器_11@27905.exe", "颜色拾取器.exe", 0, 0);
        FileInfo fileInfo2 = new FileInfo(1, "http://www.imooc.com/mobile/imooc.apk", "imooc.apk", 0, 0);
        FileInfo fileInfo3 = new FileInfo(2, "http://www.imooc.com/download/Activator.exe", "Activator.exe", 0, 0);

        fileInfos.add(fileInfo1);
        fileInfos.add(fileInfo2);
        fileInfos.add(fileInfo3);

        //创建适配器
        adapter = new FileListAdapter(this, fileInfos);
        listView.setAdapter(adapter);

    }

    private void initEvent() {

    }

    /**
     * 更新UI的广播接收器
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DownloadService.ACTION_UPDATE.equals(intent.getAction())) {
                //更新进度条
                int finished = intent.getIntExtra("finished", 0);
                int id = intent.getIntExtra("id", 0);
                adapter.updateProgress(id, finished);
            } else if (DownloadService.ACTION_FINISHED.equals(intent.getAction())) {
                //下载结束
                FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
                adapter.updateProgress(fileInfo.getId(), 0);
                Toast.makeText(MainActivity.this, fileInfos.get(fileInfo.getId()).getFileName() + "下载完毕", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
